// @ts-ignore
/* eslint-disable */
import { request } from '@umijs/max';

const API_BASE_URL = '/api';

// 获取财务统计数据
export async function fetchFinancialStats(data) {
  try {
    const response = await request(`${API_BASE_URL}/mjProductPurchase_price/queryByPage`, {
      method: 'POST',
      data: data,
    });
    return response.data;
  } catch (error) {
    console.log(error,'err')
    throw new Error('Failed to fetch financial stats');
  }
}

// 获取订单列表
export async function fetchOrderList(params) {
  try {
    const response = await request(`${API_BASE_URL}/Finance/queryFinanceByPage`, {
      method: 'POST',
      data: params,
    });
    console.log(response,'response')
    return { data: response.data.records, success: true, total: response.data.total,orderCount:response.data.orderCount,payOrderCount:response.data.payOrderCount,totalAmount:response.data.totalAmount };
  } catch (error) {
    throw new Error('Failed to fetch order list');
  }
}

// 查看订单详情
export async function viewOrder(orderNumber) {
  try {
    const response = await request(`${API_BASE_URL}/orders/${orderNumber}`, {
      method: 'GET',
    });
    return response.data;
  } catch (error) {
    throw new Error('Failed to view order');
  }
}

// 查看财务详情
export async function viewFinance(id) {
  try {
    const response = await request(`${API_BASE_URL}/Finance/detail?id=${id}`, {
      method: 'GET',
    });
    return response.data;
  } catch (error) {
    throw new Error('Failed to view finance');
  }
}

// 导出

// 导出数据
export async function exportData() {
  try {
    const response = await request(`${API_BASE_URL}/Finance/reportExport`, {
      method: 'POST',
      data: {},
      responseType: 'arraybuffer'  // 指定响应类型为 arraybuffer
    });

    // 创建一个 Blob 对象，指定正确的 MIME 类型
    const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

    // 创建一个隐藏的 <a> 标签
    const link = document.createElement('a');
    link.style.display = 'none';
    document.body.appendChild(link);

    // 使用 Blob 对象创建一个 URL
    const url = window.URL.createObjectURL(blob);
    link.href = url;
    const now = new Date();
    const year = now.getFullYear(); // 年份
    const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份（补零）
    const day = String(now.getDate()).padStart(2, '0'); // 日期（补零）

    // 拼接文件名
    const fileName = `财务统计${year}${month}${day}`;

    // 设置下载的文件名
    link.download = fileName+'.xlsx'; // 替换为你的文件名

    // 模拟点击 <a> 标签
    link.click();

    // 释放 URL 对象
    window.URL.revokeObjectURL(url);

    // 移除 <a> 标签
    document.body.removeChild(link);

    return response;
  } catch (error) {
    console.error('导出数据失败:', error);
    throw new Error('Failed to export data');
  }
}